/**
 * index.js - 首页
 * -----------------------------------
 * 18/03/14 Jerry 新增
 * 18/09/18 Jerry 新增活动楼层的查询及加载
 */
var
  helper = require('../../../utils/helper.js');

Page({

/* ------------------------------
 页面数据
 ------------------------------ */
data: {
  hidden: 'hidden' ,
  icon_img: 'https://n.hecai360.com/',
  resale_active: 0
},
/* ------------------------------
 页面加载
 ------------------------------ */
onLoad: function (opts) {

  // 查询广告（多个列表串联查询）
  this.queryADs();

  // 查询采供
  this.queryResale();

},
/* ------------------------------
 页面显示
 ------------------------------ */
onShow: function(){

  // 更新导航标题
  helper.navTitle('合采网');

  // 从其他页面（登录）跳转回首页，且要求刷新数据的，尝试刷新
  if ('refresh' == helper.pageArg('refresh'))
    this.queryADs();

},
/* ------------------------------
 下拉刷新
 ------------------------------ */
onPullDownRefresh: function(){

  // 查询广告（多个列表串联查询）
  this.queryADs();
},
/* ------------------------------
 分享小程序
 ------------------------------ */
onShareAppMessage: function(){

  var path = helper.getSharePath(this, 'index');

  console.log('index.onShareAppMessage, path => ' + path);

  return {
    title: '合采网',
    path: path
  }
},
/* ------------------------------
 查询顶部广告列表
 ------------------------------ */
queryADs: function(){
  helper.request({ url: 'wx/ads', success: this.bindADs });
},
/* ------------------------------
 绑定显示顶部广告列表
 ------------------------------ */
bindADs: function(recs){

  // 绑定数据
  this.setData({ swiperList: helper.bindFullImgUrl(recs) });

  // 绑定分类
  this.setData({ classifyList: helper.bindFullImgUrl(recs) });
  
  // 继续查询一级分类
  this.queryTypes();

},
/* ------------------------------
 查询一级分类
 ------------------------------ */
queryTypes: function() {

  helper.request({
    url: 'wx/cat/list',
    success: this.bindTypes
  });

},
/* ------------------------------
 查询一级分类
 ------------------------------ */
bindTypes: function(ret){

  // 最多显示12个
  ret = ret.slice(0, 12);

  helper.bindFullImgUrl(ret, 'typeImageUrl', 'fullTypeImageUrl');

  // 绑定分类
  this.setData({ typesLevel1: ret });
  // 继续查询活动
  this.queryActivities();

},
/* ------------------------------
 查询活动列表
 ------------------------------ */
queryActivities: function(){
  helper.request({
    url: 'wx/act/listForIndex',
    success: this.bindActivities
  });
},
/* ------------------------------
 绑定显示活动列表
 ------------------------------ */
bindActivities: function(ret){

  // 绑定数据
  this.setData({ activities: helper.bindFullImgUrl(ret, 'entryImageUrl', 'fullEntryImageUrl') });

  // 查询拼团列表（串联查询）
  this.queryPintuans();

},
/* ------------------------------
 查询拼团列表
 ------------------------------ */
queryPintuans: function(){
  helper.request({
    url: 'wx/pin/listForIndex',
    success: this.bindPintuans
  });
},
/* ------------------------------
 绑定显示拼团列表
 ------------------------------ */
bindPintuans: function(ret){

  var that = this;

  // 绑定数据
  this.setData({ pintuans: helper.bindFullImgUrl(ret) });

  // 查询品牌列表（串联查询）
  this.queryBrands();

},
/* ------------------------------
 查询品牌列表
 ------------------------------ */
queryBrands: function(){
  helper.request({
    url: 'wx/brand/listForIndex',
    success: this.bindBrands
  });
},
/* ------------------------------
 绑定显示品牌列表
 ------------------------------ */
bindBrands: function(ret){

  var that = this;

  // 绑定数据
  that.setData({ brands: helper.bindFullImgUrl(ret, 'brandImageUrl', 'fullBrandImageUrl') });

  // 推荐及新品SKU（串联查询）
  that.querySKUs(
      'recommend',
      function(){
        that.querySKUs('new', function(){
          helper.setHidden(that, false);
          wx.stopPullDownRefresh();
        })
      });

},
/* ------------------------------
 查询推荐SKU列表
 ------------------------------ */
querySKUs: function(type, callbackAfterBind){

  var that = this;

  helper.request({
    url: [ 'wx/sku/', 'recommend' == type ? 'recommendsForIndex' : 'listForIndex' ].join(''),
    data: {'pageSize': 12},
    success: function (ret) {
      // console.log(ret)
      that.bindSKUs(type, ret, callbackAfterBind)
    }
  })

},
/* ------------------------------
 绑定显示SKU列表
 ------------------------------ */
bindSKUs: function(type, recs, callback){

  var
      localData = {};

  // 推荐SKU
  if ('recommend' == type){

    // 将 recommendImgUrl 赋值给 imgUrl 字段
    helper.each(recs, function(idx, rec){ rec.imgUrl = rec.recommendImgUrl });
    // 设给 recommendSKUs
    localData.recommendSKUs = recs;
  }
  else {
    // 设给 newSKUs
    localData.newSKUs = recs;
  }

  // 绑定完整图片URL
  recs = helper.bindFullImgUrl(recs);

  // 绑定数据
  this.setData(localData);

  // 回调函数
  if (typeof callback == 'function')
    callback();

},
/* ------------------------------
 大图幻灯片切换
 ------------------------------ */
handleSwiperChange: function(e){
  this.setData({ swiperIndex: e.detail.current + 1 });
},
/* ------------------------------
 处理广告Click
 ------------------------------ */
handleADClick:function(e){

  var
      lnkUrl = e.currentTarget.dataset.lnkUrl,
      m;

  if (!lnkUrl)
    return;

  // SKU详情页
  m = /\bskuId=([a-z0-9]+)/ig.exec(lnkUrl);
  if (m) {
    helper.navigateFormat('skuDetail', { skuId: m[1] });
    return;
  }

  // 拼团详情页
  m = /\bpintuanId=([a-z0-9]+)/ig.exec(lnkUrl);
  if (m) {
    helper.navigateFormat('pintuanDetail', { pintuanId: m[1] });
    return;
  }

  // 活动详情页
  m = /\/act\/([^.]+)\.html/ig.exec(lnkUrl);
  if (m) {
    helper.navigateFormat('activityDetail', { urlCode: m[1] });
    return;
  }


},
/* ------------------------------
 处理搜索框Click
 ------------------------------ */
handleSearchClick: function(){
  helper.navigateTo('skuSearch');
},
/* ------------------------------
 处理一级分类Click
 ------------------------------ */
handleTypesClick: function(e){

  var key = e.currentTarget.dataset.key;

  if (!key)
    return;

  helper.navigateFormat('skuCategory', { type1: key });

},
/* ------------------------------
 跳转到拼团列表
 ------------------------------ */
redirectPintuanAll: function(e){
  helper.switchTab('pintuanAll');
},
/* ------------------------------
 查询采供列表
 ------------------------------ */
queryResale: function(){

  helper.request({
    url: 'wx/demand/all',
    data: { pageSize: 4, pageIndex: 0 },
    success: this.bindResale
  });

},
/* ------------------------------
 绑定采购列表
 ------------------------------ */
bindResale: function(ret){

  console.log(ret);

  // 绑定数据
  helper.bindD2Str(ret.records, 'expireTime');

  this.setData({ demandList: ret });

},
/* ------------------------------
 供求信息tab切换
 ------------------------------ */
resTabClick:function (e) {
  var that = e.target.dataset.key;

  if (that === 'demand')
    this.setData({ resale_active: 0 });

  if (that === 'supply')
    this.setData({ resale_active: 1 });
}

})
